#include "ocv_service_impl.h"
#include "config_loader.h"
#include <iostream>
#include <vector>

OcvServiceImpl::OcvServiceImpl(const std::string& video_source, int jpeg_quality) :
    m_video_device(video_source), m_jpeg_quality(jpeg_quality)
{
    m_cap = cv::VideoCapture(m_video_device);
    if (!m_cap.isOpened()) {
        std::cerr << "Failed to open video device: " << m_video_device << std::endl;
        exit(1);
    }
}

Status OcvServiceImpl::GetFrame(ServerContext* context, const VoidRequest* request, JpegFrameResponse* response)
{
    cv::Mat frame;
    m_cap >> frame;
    auto enc_param = std::vector<int>({cv::IMWRITE_JPEG_QUALITY, m_jpeg_quality});
    std::vector<uchar> buffer;
    cv::imencode(".jpg", frame, buffer, enc_param);
    response->set_data(buffer.data(), buffer.size());
    return Status::OK;
}
